package com.jubaopen.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.RandomStringUtils;

import tools.PagedList;

import com.jubaopen.bean.InviteCode;
import com.jubaopen.dao.InviteCodeDAO;

public class InviteCodeService {

	private InviteCodeDAO inviteCodeDAO;

	public void setInviteCodeDAO(InviteCodeDAO inviteCodeDAO) {
		this.inviteCodeDAO = inviteCodeDAO;
	}

	public int addInviteCode(InviteCode inviteCode) {
		return inviteCodeDAO.add(inviteCode);
	}

	public int updateInviteCode(InviteCode inviteCode) {
		return inviteCodeDAO.update(inviteCode);
	}

	public InviteCode getInviteCode(String code) {
		return inviteCodeDAO.getByCode(code);
	}

	public boolean isGenCodePermit(Map<String, Object> queryMap){
		int count = inviteCodeDAO.getNoActiveCount(queryMap);
		if (count == 0) {
			return true;
		}
		return false;
	}
	
	public PagedList<InviteCode> getCodeList(Map<String, Object> queryMap,
			int pageIndex, int pageSize) {
		int skip = pageIndex * pageSize;
		List<InviteCode> codeList = new ArrayList<InviteCode>();
		queryMap.put("skip", skip);
		queryMap.put("pageSize", pageSize);
		try {
			codeList = inviteCodeDAO.getPagedList(queryMap);
			PagedList<InviteCode> ret = new PagedList<InviteCode>();
			ret.setList(codeList);
			
			int count = inviteCodeDAO.getCount(queryMap);
			ret.setCount(count);
			return ret;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public void doGenCode(int userId, int num) {
		for (int i = 0; i < num; i++) {
			InviteCode inviteCode = new InviteCode();
			String code = RandomStringUtils.random(8, true, true);
			inviteCode.setInvitorId(userId);
			inviteCode.setInviteCode(code);
			inviteCode.setGenerateTime(new Date());
			inviteCodeDAO.add(inviteCode);
		}
	}
}
